﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Money.Interfaces;
using Money.Data;
using One.Web;
using One.Framework;

public partial class Admin_AccountManagement : System.Web.UI.Page
{
    #region fields

    private IAccountService accountService;
    private ICurrencyService currencyService;
    private IAccountTypeService accountTypeService;
    protected List<Account> accounts;
    private List<Currency> currencies;
    private List<AccountType> accountTypes;
    private AccountOrderBy orderBy;
    private OrderDirection orderDirection;
    private string redirectUrl = "AccountManagement.aspx";
    private int success;
    private string errorIds;
    private int accountType;
    private int currencyType;
    private int totalRecords;

    #endregion

    #region events

    protected void Page_Load(object sender, EventArgs e)
    {
        accountService = ServiceFactory.Create<IAccountService>();
        accountTypeService = ServiceFactory.Create<IAccountTypeService>();
        currencyService = ServiceFactory.Create<ICurrencyService>();

        GetParams();
        LoadData();
        if(!IsPostBack)
            UpdateView();
    }

    protected void Search(object sender, EventArgs e)
    {
        List<One.Web.QueryStringParameter> listParam = new List<One.Web.QueryStringParameter>();
        accountType = int.Parse(cbAccountType.SelectedValue);
        currencyType = int.Parse(cbCurrencyType.SelectedValue);

        if(accountType != 0)
            listParam.Add(new One.Web.QueryStringParameter("account", accountType.ToString()));
        if(currencyType != 0)
            listParam.Add(new One.Web.QueryStringParameter("currency", currencyType.ToString()));
        string paramUrl = QueryStringUtility.BuildQueryString(listParam);
        if (!string.IsNullOrEmpty(paramUrl))
        {
            Response.Redirect(string.Format("{0}?{1}", redirectUrl, paramUrl));
        }
        Response.Redirect(redirectUrl);    
    }

    protected void DeleteAccounts(object sender, EventArgs e)
    {
        string[] deleteIdString;
        string idError = "";
        if (string.IsNullOrEmpty(Request.Form["selectedItems"]))
        {
            return;
        }
        deleteIdString = Request.Form["selectedItems"].Split(',');
        for (int i = 0; i < deleteIdString.Length; i++)
        {
            int id = 0;
            try
            {
                if (!int.TryParse(deleteIdString[i], out id))
                    id = 0;
                if(accountService.CanDelete(id))
                    accountService.DeleteAccount(id);
                else
                    idError = string.Format("{0},{1}", idError, id);
            }
            catch
            {
                if (id != 0)
                    idError = string.Format("{0},{1}", idError, id);
            }
        }
        if (!string.IsNullOrEmpty(idError))
        {
            idError = idError.TrimStart(',');
            Response.Redirect(string.Format("{0}?success={1}&idserror={2}", redirectUrl, -3, idError));
        }
        else
        {
            Response.Redirect(string.Format("{0}?success={1}", redirectUrl, 3));
        }
    }

    #endregion

    #region private functions

    private void GetParams()
    {
        orderBy = QueryStringUtility.GetEnum<AccountOrderBy>("OrderBy", AccountOrderBy.AccountId.ToString());
        orderDirection = QueryStringUtility.GetEnum<OrderDirection>("OrderDirection", OrderDirection.ASC.ToString());
        success = QueryStringUtility.GetInt32("success", 0);
        errorIds = QueryStringUtility.GetString("idserror", "");
        accountType = QueryStringUtility.GetInt32("account", 0);
        currencyType = QueryStringUtility.GetInt32("currency", 0);
    }

    private void LoadData()
    {
        string strOrderBy = orderBy.ToString();
        if (orderBy == AccountOrderBy.AccountType1 || orderBy == AccountOrderBy.Currency)
            strOrderBy += ".Name";
        accounts = accountService.GetAccounts(WebSession.CurrentUser.UserId, accountType, currencyType, strOrderBy, orderDirection.ToString(), pager.PageIndex,
                                        MoneyManagerConfig.AdminPageSize, out totalRecords);
        accountTypes = accountTypeService.GetAccountTypes();
        currencies = currencyService.GetCurrencies();
    }

    private void UpdateView()
    {
        AddAccountTypes();
        AddCurrencies();
        repeaterAccounts.DataSource = accounts;
        repeaterAccounts.DataBind();

        (Master as Admin_MasterPage).SelectedTab = "accountManagement";
        pageTitle.Text = Resources.Strings.AccountManagement;
        pager.TotalRecords = totalRecords;
        pager.PageSize = MoneyManagerConfig.AdminPageSize;

        messageLabel.Visible = success != 0;

        switch (success)
        {
            case 1:
                messageLabel.Text = Resources.Strings.AddAccountSuccess;
                break;
            case 2:
                messageLabel.Text = Resources.Strings.UpdateAccountSuccess;
                break;
            case 3:
                messageLabel.Text = Resources.Strings.DeleteAccountSuccess;
                break;
            case -1:
                messageLabel.Text = Resources.Strings.AddAccountUnSuccess;
                break;
            case -2:
                messageLabel.Text = Resources.Strings.UpdateAccountUnSuccess;
                break;
            case -3:
                messageLabel.Text = string.Format(Resources.Strings.DeleteAccountUnSuccess, errorIds);
                break;

        }
    }

    private void AddCurrencies()
    {
        currencies.Insert(0, new Currency() { Id = 0, Name = "All" });
        cbCurrencyType.DataSource = currencies;
        cbCurrencyType.DataTextField = "Name";
        cbCurrencyType.DataValueField = "Id";
        cbCurrencyType.DataBind();

        cbCurrencyType.SelectedValue = currencyType.ToString();
    }

    private void AddAccountTypes()
    {
        accountTypes.Insert(0, new AccountType() { Id = 0, Name = "All" });
        cbAccountType.DataSource = accountTypes;
        cbAccountType.DataTextField = "Name";
        cbAccountType.DataValueField = "Id";
        cbAccountType.DataBind();

        cbAccountType.SelectedValue = accountType.ToString();
    }

    #endregion

    #region public functions

    public string GetOrderByLink(string propertyName)
    {
        OrderDirection newOrderDirection = orderDirection;
        string url = CreateUrlParams();
        if (propertyName == orderBy.ToString())
        {
            newOrderDirection = orderDirection == OrderDirection.ASC ? OrderDirection.DESC : OrderDirection.ASC;
        }
        return String.Format("{0}{4}OrderBy={1}&OrderDirection={2}&Page={3}", url,
            propertyName, newOrderDirection.ToString(), pager.PageIndex, url.IndexOf('?') > 0 ? "&" : "?");
    }

    private string CreateUrlParams()
    {
        return redirectUrl;
    }

    public string GetOrderDirectionIndicator(string propertyName)
    {
        if (propertyName == orderBy.ToString())
        {
            return String.Format("<img src=\"../images/{0}.gif\" alt=\"{0}\" align=\"absmiddle\" />", orderDirection);
        }
        return "";
    }

    #endregion
}
